<?php
	//session_start();
	$con = mysql_connect("127.0.0.1","root","");
	  
	if (!$con) {
		error_log("Could not connect: " . mysql_error());
	}

	mysql_select_db("yeoldeguilde", $con);
	
	$uploadDir = "C:/wamp/www/uploads/";
	$lastUpdated = date( 'Y-m-d H:i:s', time() );
	$bankerList = array();
	$itemList = array();
	$bankerList[0] = 'Guildelw';
	$bankerList[1] = 'Guildebags';
	$bankerList[2] = 'Guildeeng';
	$bankerList[3] = 'Guildeench';
	$bankerList[4] = 'Guildebags';
	$bankerList[5] = 'Guilderaid';
	$bankerList[6] = 'Guildeequip';
	if (isset($argv[2]) && ($argv[2] == "newfile")) {
		// Break apart file path string
		$fileStrings = explode("\\",$argv[1]);
		// Get the part after the last '\'; i.e., the filename
		$lastkey = array_pop(array_keys($fileStrings));
		$fileName = $fileStrings[$lastkey];
		
		// Break apart name stem - timestamp
		$nameChunks = explode("-",$fileName);
		
		//$nameChunks[0] is the part before the timestamp	
		echo "fileName=".$fileName."\n";
		echo "$nameChunks[0]=".$nameChunks[0]."\n";		
		echo '\n'.'\n'."Parsing ".$fileName." at ".$lastUpdated.'\n'.'\n';		
		loadItems("BankItems-".$nameChunks[1]);
		loadCharItems("CharProfile-".$nameChunks[1]);
		doItemSql();
		loadGuild("CharProfile-".$nameChunks[1]);		
		loadMail("MailTo-".$nameChunks[1]);
		/* Problems with my directory monitor program makes this dynamic loading fail
		switch ($nameChunks[0]) {
		case "BankItems":
			loadItems($nameChunks[0]+"-"+$nameChunks[1]);
			break;
		case "CharProfile":
			loadGuild($fileName);
			break;
		case "MailTo":
			loadMail($fileName);
			break;
		}
		*/
	} else {
		// TODO: ajax requests here
		/*
		$logFile = 'logFile';
		$res = json_decode(stripslashes($_POST['data']), true);
		error_log("result: ".$_POST['data'].", res=".json_encode($res), 3, $logFile);
		error_log(", sales1_lastname: ".$res['sales'][1]['lastname'], 3, $logFile);
		error_log("\n", 3, $logFile);
		 
		header("Content-type: text/plain");
		echo json_encode($res);
		*/	
		$result = mysql_query("SELECT * FROM bankitems ORDER BY banker DESC ");
		$return = array();
		while($row = mysql_fetch_array($result)) {
			array_push($return, $row);
		}
		echo json_encode($return);


	}
	
	mysql_close($con);
	
function loadItems($fileName) {
		global $uploadDir, $itemList;
		//$itemList = array();
			echo "Moving $fileName to uploads archive...\n";
		rename ($uploadDir."temp/".$fileName, $uploadDir.$fileName);
	if ($fileData = file_get_contents($uploadDir.$fileName, true)) {
		$bankItemData = makePhpArray($fileData);
		$bankers = $bankItemData["BankItems_Save"];
		$bankerNames = array_keys($bankers);			
		$bankerIndex = 0;
		$bankerList = array();
		foreach ($bankers as $banker) {	//loop through each banker
			$temp = explode("|",$bankerNames[$bankerIndex]);
			$currentBanker = $temp[0];
			array_push($bankerList, $currentBanker);
			foreach ($banker as $key => $item) {
				if ($key == "money") {
					//echo "HAY! ".$currentBanker." has: ".$item." monies...\n";				
				} else if (strstr($key, "Bag")) {					
					//echo "<h1>NOT AN ARARY OR AN MONEY \nGOTSA BEA BAG\n</h1>";	
					//echo "<pre>";
					//print_r($item);
					//echo "</pre>\n";		
					foreach ($item as $itemInBag) {
						parseItem($itemInBag,$currentBanker, $itemList);
					}
				} else {
					//echo "parseItems();\n";
						parseItem($item,$currentBanker, $itemList);
				}
			}			
			$bankerIndex++;
		}	
		
		
		//var_dump($bankerList);
		
		$query = "UPDATE information SET bankers = '".serialize($bankerNames)." 'WHERE id = '1'";
		if (!mysql_query($query,  $GLOBALS['con'])) {
					echo 'Error: ' . mysql_error()."\n";
		}
		
		$query = "UPDATE information SET lastUpdated = '".$GLOBALS['lastUpdated']." 'WHERE id = '1'";
		if (!mysql_query($query,  $GLOBALS['con'])) {
					echo 'Error: ' . mysql_error()."\n";
		}
		
		//var_dump($itemList);
	} else {
		echo "No new data to parse for bank items....\n";
	}
}

function loadCharItems($fileName) {
	global $uploadDir, $bankerList, $itemList;
	if ($fileData = file_get_contents($uploadDir."temp/".$fileName, true)) {
		$charItemData = makePhpArray($fileData);
		//echo "<pre>";
		//print_r($charItemData['myProfile']['Rebirth']['Tooba']['Money']);
		//print_r($charItemData['myProfile']['Rebirth']['Tooba']['Inventory']['Bag2']['Contents']);
		//echo "</pre>";
		//echo "<pre>";
		foreach ($bankerList as $banker) {
			
			$curInventory = $charItemData['myProfile']['Rebirth'][$banker]['Inventory'];
			//print_r($curInventory);
			foreach ($curInventory as $bag => $contents) {
				//echo "Banker: ".$banker." Bag:".$bag;
				//print_r($contents);
				foreach ($contents as $bag) {
					if (is_array($bag)) {
						foreach ($bag as $item) {
							//print_r($item);
							parseCharItem($item,$banker, $itemList);
						}
					} else {
						
						echo "Bag -> not array ?? @_@\m\m";
						print_r($bag);
						//echo "<br><hr>";
					}
				}
			}
		}
		print_r($itemList);
		//echo "</pre>";
	}
}
	
function parseCharItem($item, $currentBanker, &$itemList) {
	//if (is_array($item)) {
		$tempItem = explode(':', $item['Item']);
		//print_r($item);
		$name = mysql_real_escape_string($item['Name']);
		
		$count = $item['Quantity'];
		$itemId = $tempItem[0];
		$icon = $item['Texture'];
		// charprofile stores first two hex digits as alpha
		$color = substr($item['Color'], 2);
		
		$isDuplicate = false;
		foreach ($itemList as &$dupItem) {
			if (($dupItem['itemName'] == $name) && ($dupItem['banker'] == $currentBanker)) {
				$dupItem['count'] += $count;
				$isDuplicate = true;
			}
		}
		if (!$isDuplicate) {
			$parsedItem = array();
			$parsedItem['itemName'] = $name;
			$parsedItem['count'] = $count;
			$parsedItem['itemID'] = $itemId;
			$parsedItem['icon'] = $icon;
			$parsedItem['color'] = $color;
			$parsedItem['banker'] = $currentBanker;
			$parsedItem['lastUpdated'] = $GLOBALS['lastUpdated'];
			array_push($itemList, $parsedItem);
		}
	//} else {
	//	echo "UNKNOWN ITEM CASE<br>";
	//}

}

function doItemSql() {
	global $itemList;
	foreach ($itemList as $item) {
		$query = "INSERT INTO bankItems (id, banker, itemName, itemCount, itemId, icon, color, lastUpdated) VALUES ".
				 "(NULL, '".$item['banker']."', '".$item['itemName']."', '".$item['count']."', '".$item['itemID']."', '".
				 $item['icon']."', '".$item['color']."', '".$GLOBALS['lastUpdated']."');";
		echo $query."\n";
		if (!mysql_query($query,  $GLOBALS['con'])) {
			echo 'Error: ' . mysql_error()."\n";
		}	
	}
}

function loadMail($fileName) {
global $uploadDir;
	echo "Parsing mail log....\n";
			echo "Moving $fileName to uploads archive...\n";
		rename ($uploadDir."temp/".$fileName, $uploadDir.$fileName);
		//sleep(1);    // this does the trick
	if ($fileData = file_get_contents($uploadDir.$fileName, true)) {
		$mailToData = makePhpArray($fileData);
		echo "</pre>";
			foreach ($mailToData['MailTo_Log'] as $key => $value) {
				$date = date( 'Y-m-d H:i:s', strtotime($value['date']) );
				$query = "INSERT INTO mail (id, target, sender, item, date, due, lastUpdated) VALUES ".
				 "(NULL, '".$value['to']."', '".$value['from']."', '".$value['item']."', '".$date."', '".$value['due']."', '".$GLOBALS['lastUpdated']."');";
				echo $query."\n";
				
				//if (!mysql_query($query,  $GLOBALS['con'])) {
				//	echo 'Error: ' . mysql_error()."\n";
				//}
			}

	} else {
		echo "No new data to parse for mail....\n";
	}
}

function loadGuild($fileName) {
	global $uploadDir;
	echo "Parsing guild roster....\n";
	echo "Parsing mail log....\n";
	echo "Moving $fileName to uploads archive...\n";
			//rename ($uploadDir."temp/".$fileName, $uploadDir.$fileName);
	rename ($uploadDir."temp/".$fileName, $uploadDir.$fileName);
	if ($fileData = file_get_contents($uploadDir.$fileName, true)) {
		$profileData = makePhpArray($fileData);
		
		// get last time items have been updated
		$query = "SELECT lastUpdated from information WHERE id = '1'";
		$result = mysql_query($query,  $GLOBALS['con']);
		$row = mysql_fetch_array($result);
		$lastUpdated = $row['lastUpdated'];
		// Gather general information
		$guildData = $profileData["myProfile"]["Rebirth"]["Guild"];
		//$motd = $guildData['Motd'];
		$numMembers = $guildData['NumMembers'];
		$numAccounts = $guildData['NumAccounts'];
		$rank1 = $guildData['Ranks']['Index']['Rank1']['Title'];
		$rank2 = $guildData['Ranks']['Index']['Rank2']['Title'];
		$rank3 = $guildData['Ranks']['Index']['Rank3']['Title'];
		$rank4 = $guildData['Ranks']['Index']['Rank4']['Title'];
		$rank5 = $guildData['Ranks']['Index']['Rank5']['Title'];
		$rank6 = $guildData['Ranks']['Index']['Rank6']['Title'];
		$query = "Update information SET numMembers = '".$numMembers."', numAccounts = '".$numAccounts."', rank1 = '".$rank1."', ".
				 "rank2 = '".$rank2."', rank3 = '".$rank3."', rank4 = '".$rank4."', rank5 = '".$rank5."', rank6 = '".$rank6."'";
				
		echo $query."\n";
		mysql_query($query,  $GLOBALS['con']);
		//			echo 'Error: ' . mysql_error()."\n";
		//}
		
		
		// parse members
		$members = $guildData["Members"];
		echo "Parsing guild roster....\n";
		foreach ($members as $member) {
			$name = $member["Name"];
			$rank = $member["Rank"];
			$rank_index = $member["RankIndex"];
			$level = $member["Level"];
			if (isNewMemeber($name)) {
				$class = $member["Class"];
				$query = "INSERT INTO members (id, name, password, newUser, rank, rank_index, class, level) VALUES ".
						 "(NULL, '".$name."', '".md5("yeolde".$name)."', '1', '".$rank."', ".
						 $rank_index.", '".$class."', ".$level.");";
				echo $query."\n";
				//$query = mysql_real_escape_string($query);
				if (!mysql_query($query, $GLOBALS['con'])) {
					echo 'Error: ' . mysql_error();
				}	
			} else {
				$query = "UPDATE members SET rank = '".$rank."' WHERE name = '".$name."'";
				echo $query."";
				if (!mysql_query($query, $GLOBALS['con'])) {
					echo 'Error: ' . mysql_error();
				}
				$query = "UPDATE members SET rank_index = '".$rank_index."' WHERE name = '".$name."'";
				echo $query."";
				if (!mysql_query($query, $GLOBALS['con'])) {
					echo 'Error: ' . mysql_error();
				}
				$query = "UPDATE members SET level = '".$level."' WHERE name = '".$name."'";
				echo $query."";
				if (!mysql_query($query, $GLOBALS['con'])) {
					echo 'Error: ' . mysql_error();
				}
			}
		}			
	} else {
		echo "Cannot load:".$filename."\n";
	}
}

function isNewMemeber($name) {
	$query = 'SELECT * FROM members WHERE name="'.$name.'"';
	//echo $query;
	$result = mysql_query($query,  $GLOBALS['con']);			
	$numResults = mysql_num_rows($result);
	
	if($numResults < 1) {
		return true;
	}
	
	return false;

}

function parseItem($item,$currentBanker, &$itemList) {	
	//check for money and bank bag special-cases
	if (is_array($item)) {
		$tempItem = explode("|",$item['link']);
		$linkChunks = explode(":",$tempItem[2]);
		
		$name = mysql_real_escape_string(substr($tempItem[3], 2));
		$name = rtrim($name, "]");
		
		$count = $item['count'];
		$itemID = $linkChunks[1];
		$icon = $item['icon'];
		$color = substr($tempItem[1], 3);
		//echo "Banker: ".$currentBanker." Name: ".$name." count: ".$count." itemID: ".$itemID." icon: ".$icon." color: ".$color."\n";
		
		$isDuplicate = false;
		
		foreach ($itemList as &$dupItem) {
			if (($dupItem['itemName'] == $name) && ($dupItem['banker'] == $currentBanker)) {
				$dupItem['count'] += $count;
				$isDuplicate = true;
			}
		}
		if (!$isDuplicate) {
			$parsedItem = array();
			$parsedItem['itemName'] = $name;
			$parsedItem['count'] = $item['count'];
			$parsedItem['itemID'] = $linkChunks[1];
			$parsedItem['icon'] = $item['icon'];
			$parsedItem['color'] = substr($tempItem[1], 3);
			$parsedItem['banker'] = $currentBanker;
			$parsedItem['lastUpdated'] = $GLOBALS['lastUpdated'];
			array_push($itemList, $parsedItem);
		}
	} else {
		//echo "<p>DEBUG: Parsing error in bankItems... ".$key." => ".$value."</p>";
	}
	
}

function trimval($str)
{
  $str = trim($str);
  if (substr($str,0,1)=="\""){
    
    $str  = trim(substr($str,1,strlen($str)));
  }
  if (substr($str,-1,1)==","){
    $str  = trim(substr($str,0,strlen($str)-1));
  }

  if (substr($str,-1,1)=="\""){
    $str  = trim(substr($str,0,strlen($str)-1));
  }
  
  if ($str =='false') 
  {
    $str = false;
  }
  if ($str =='true') 
  {
    $str = true;
  }
  
  return $str;
}

/*
  function array_id(string)
  
  extracts the Key-Value for array indexing 
  String-Example:
    Input: ["Key"]
    Output: Key    
  Int-Example:
    Input: [0]
    Output: 0    
*/
function array_id($str)
{
  $id1 = sscanf($str, "[%d]");  
  if (strlen($id1[0])>0){
    return $id1[0];    
  }
  else
  {
    if (substr($str,0,1)=="[")
    {
      $str  = substr($str,1,strlen($str));
    }
    if (substr($str,0,1)=="\"")
    {
      $str  = substr($str,1,strlen($str));
    }
    if (substr($str,-1,1)=="]")
    {
      $str  = substr($str,0,strlen($str)-1);
    }
    if (substr($str,-1,1)=="\"")
    {
      $str  = substr($str,0,strlen($str)-1);
    }
    return $str;
  } 
}

/*
  function luaparser(array, arrayStartIndex)
  
  recursive Function - it does the main work
*/
function luaparser($lua, &$pos)
{
  $parray = array();
  $stop = false;
  if ($pos < count($lua)) 
  {
    for ($i = $pos;$stop ==false;)
    {
      if ($i >= count($lua)) { $stop=true;}
      $strs = @explode("=",utf8_decode($lua[$i]));
      if (@trim($strs[1]) == "{"){
        $i++;
        $parray[array_id(trim($strs[0]))]=luaparser($lua, $i);
      } 
      else if (trim($strs[0]) == "}" || trim($strs[0]) == "},")
      {
        //$i--;
        $i++;
        $stop = true;
      }
      else
      {
        $i++;
        if (strlen(array_id(trim($strs[0])))>0 && strlen($strs[1])>0) 
        {
          $parray[array_id(trim($strs[0]))]=trimval($strs[1]);
        }
      } 
    }
  }
  $pos=$i;
  return $parray;
}

/*
  function makePhpArray($input)
  
  thst the thing to call :-)
  
  $input can be 
    - an array with the lines of the LuaFile
    - a String with the whole LuaFile
    - a Filename
  
*/
function makePhpArray($input){
  $start = 0;
  if (is_array($input))
  {    
    return luaparser($input,$start);
  } 
  elseif (is_string($input))
  {
    if (@is_file ( $input ))
    {
      return luaparser(file($input),$start);
    }
    else
    {
      return luaparser(explode("\n",$input),$start);
    }
  }  
}

	
?>